package com.woniu.job.util;


import com.woniu.job.entity.Resume;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.bouncycastle.util.encoders.Base64;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author : 陈思宇
 * @date :2019/12/27
 */

public class WordUtil {

    /**
     * 生成word文件
     *
     * @param dataMap      word中需要展示的动态数据，用map集合来保存
     * @param templateName word模板名称，例如：test.ftl
     * @param filePath     文件生成的目标路径，例如：D:/wordFile/
     * @param fileName     生成的文件名称，例如：test.doc
     */
    @SuppressWarnings("unchecked")
    public static Boolean createWord(Map dataMap, String templateName, String filePath, String fileName) {
        try {
            //创建配置实例
            Configuration configuration = new Configuration();

            //设置编码
            configuration.setDefaultEncoding("UTF-8");

            //ftl模板文件
            configuration.setClassForTemplateLoading(WordUtil.class, "/");

            //获取模板
            Template template = configuration.getTemplate(templateName);

            //输出文件
            File outFile = new File(filePath + File.separator + fileName);

            //如果输出目标文件夹不存在，则创建
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }

            //将模板和数据模型合并生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));


            //生成文件
            template.process(dataMap, out);

            //关闭流
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 对数据进行处理
     * @param resume
     * @return
     */
    public Boolean getData(Resume resume) {
        Map<String, Object> dataMap = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //LocalDate转为date
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate localDate = resume.getBirthdate();
        ZonedDateTime zdt = localDate.atStartOfDay(zoneId);
        Date date = Date.from(zdt.toInstant());

        dataMap.put("realName", resume.getRealName());
        dataMap.put("gender", resume.getGender());
        dataMap.put("birthdate", sdf.format(date));
        dataMap.put("height", resume.getHeight());
        dataMap.put("marriage", resume.getMarriage());
        dataMap.put("workExp", resume.getWorkExp());
        dataMap.put("region", resume.getRegion());
        dataMap.put("education", resume.getEducation());
        dataMap.put("skill", resume.getSkill());
        dataMap.put("telephone", resume.getTelephone());
        dataMap.put("email", resume.getEmail());
        dataMap.put("address", resume.getAddress());
        dataMap.put("qq", resume.getQq());
        dataMap.put("salaryExpectation", resume.getSalaryExpectation());
        String base64 = this.getBase64(resume.getPhoto());
        dataMap.put("photo", base64);
        String name = resume.getRealName() + "-简历.doc";
        return WordUtil.createWord(dataMap, "freeMark.ftl", "D:/wordFile/", name);
    }

    /**
     * 转换为base64编码
     * @param imgUrl
     * @return base64
     */
    private String getBase64(String imgUrl) {
        if (imgUrl == null || imgUrl == "") {
            return "";
        }
        File file = new File(imgUrl);
        if (!file.exists()) {
            return "";
        }
        InputStream in = null;
        byte[] data = null;

        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException var8) {
            var8.printStackTrace();
        }

        byte[] result = Base64.encode(data);
        return new String(result);
    }
}
